// pages/stepStudy/index.js
const app = getApp();// 云：add this before every page //
const HTTP = require('../../utils/http')
const API = require('../../utils/api')
const plugin = requirePlugin("WechatSI")

const backgroundAudioManager = wx.getBackgroundAudioManager()
backgroundAudioManager.title = '银龄助手语音播报'

Page({

  /**
   * 页面的初始数据
   */
  data: {
    safeBottom: app.globalData.safeBottom, // 云：add this before every page //
    safeTop: app.globalData.safeTop,

    percent: 50,
    count: 0,
    maxStep: 0,
    maxStepLastTime:0,
    imgList: [],
    detailData: [],
    height:0,
    width:0,
    ctx:'',
    canvas:'',
    need_click_x:-1,
    need_click_y:-1,

    paly_type: 'wait',
    play_list:[],
  },

  tts(lang, content, index){
    plugin.textToSpeech({
      lang: lang,
      content: content,
      success: resTrans => {
        if(resTrans.retcode == 0) {
          console.log("文字转语音成功！", resTrans)
          if(index>this.data.play_list.length-1){
            let tmpDialogList = this.data.play_list.slice(0)
            tmpDialogList.push({
              translateVoicePath: resTrans.filename,
              translateVoiceExpiredTime: resTrans.expired_time || 0
            })
            this.setData({
              play_list: tmpDialogList,
            })
            this.tapSpeech()
          }
          else{
            let tmpDialogList = this.data.play_list.slice(0)
            let tmpTranslate = {
              translateVoicePath: resTrans.filename,
              translateVoiceExpiredTime: resTrans.expired_time || 0
            }
            tmpDialogList[index] = tmpTranslate
            this.setData({
              play_list: tmpDialogList,
            })
          }
        } else {
          console.warn("语音合成失败", resTrans)
          if(index>this.data.play_list.length-1){
            let tmpDialogList = this.data.play_list.slice(0)
            tmpDialogList.push({
              translateVoicePath: "",
              translateVoiceExpiredTime: 0
            })
            this.setData({
              play_list: tmpDialogList,
            })
          }
        }
      },
      fail: function(resTrans) {
        console.warn("语音合成失败", resTrans)
        if(index>this.data.play_list.length-1){
          let tmpDialogList = this.data.play_list.slice(0)
          tmpDialogList.push({
            translateVoicePath: "",
            translateVoiceExpiredTime: 0
          })
          this.setData({
            play_list: tmpDialogList,
          })
        }
      }
    })
  },

  //点击讲解
  tapSpeech(){
    // wx.showToast({
    //   title: '暂不支持讲解',
    //   icon: "error"
    // })
    console.log("点击讲解按钮!",this.data.playType)

    let index = this.data.count
    let nowTime = parseInt(+ new Date() / 1000)
    let voicePath =  this.data.play_list[index].translateVoicePath
    let voiceExpiredTime = this.data.play_list[index].translateVoiceExpiredTime

      if(this.data.playType == 'playing') {
        backgroundAudioManager.stop()
        this.playAnimationEnd()
      } else if(nowTime < voiceExpiredTime) {
        this.autoPlayTranslateVoice(voicePath)
      } else {
        this.setData({
          playType: 'loading',
        })
        // let lto = item.lto || 'en_US'
        let lto = 'zh_CN'
        let content_text = "第"+(this.data.count+1).toString()+"步" + this.data.imgList[this.data.count].description

        this.tts(lto, content_text, index)
      }
    
  },
   /**
     * 播放背景音乐
     */
    autoPlayTranslateVoice: function (path) {
      let play_path = path
      let that = this
      console.log("播放路径是：",play_path)

      if(!play_path) {
        console.warn("no translate voice path")
        return
      }

      backgroundAudioManager.onEnded(function() {
        console.log("play voice end")
        that.playAnimationEnd()
      })

      that.playAnimationStart()
      backgroundAudioManager.src = play_path
    },

    /**
     * 开始播放
     */
    playAnimationStart: function() {
      this.setData({
        playType: 'playing',
      })

    },

    /**
     * 结束播放
     */
    playAnimationEnd: function() {
        this.setData({
          playType: 'wait',
        })
    },
 

  next() {
    backgroundAudioManager.stop()
    this.playAnimationEnd()
    if (this.data.count < this.data.imgList.length - 1) {
      this.setData({
        count: this.data.count + 1
      })
      if(this.data.count > this.data.maxStep){
        this.setData({
          maxStep: this.data.count
        })
      }
      if(this.data.play_list.length-1<this.data.count)
      {
        // let lto = item.lto || 'en_US'
        let lto = 'zh_CN'
        let content_text = "第"+(this.data.count+1).toString()+"步" + this.data.imgList[this.data.count].description

        this.tts(lto, content_text, this.data.count)
      }
      else{
        // 自动播放
      this.tapSpeech()
      }
    } else {
      wx.navigateTo({
        url: `/pages/studyFinsh/index?id=${this.data.detailData.id}`,
      })
    }
    // 绘画第N步
    if(this.data.ctx){
        this.myDraw1()
    }
  },
  back() {
    backgroundAudioManager.stop()
    this.playAnimationEnd()
    if (this.data.count - 1 >= 0) {
      this.setData({
        count: this.data.count - 1
      })
    } else {
      wx.navigateBack()
    }
    // 自动播放
    this.tapSpeech()

    // 绘画第N步
    if(this.data.ctx){
        this.myDraw1()
    }
  },

  reStudy() {
    this.setData({
      count: 0
    })
    // 绘画第N步
    if(this.data.ctx){
        this.myDraw1()
    }
  },

  // 上传课程学习信息
  uploadStep(){
    // if(this.data.maxStepLastTime!==this.data.maxStep){
      wx.request({
        url: API.UpdateProgress,
        header:{
          "Authorization": 'Bearer '+wx.getStorageSync('accessTokenData').accessToken
        },
        method: "put",
        data:{
          courseItemId: this.data.imgList[this.data.maxStep].id,
          finished: this.data.detailData.finished ? true:this.data.imgList.length-1 === this.data.maxStep,
          id: this.data.imgList[this.data.maxStep].courseId,
          progress: (this.data.maxStep+1)/this.data.imgList.length,
        },
        success: (res) => {
          console.log("调用更新学习状态接口返回的信息是：",res)
          this.setData({
            maxStepLastTime: this.data.maxStep
          })
        },
        fail: (err) => {
        },
        complete:()=>{
          
        }
      })
    // }
  },
  //点击引导区域
  tochCanvasEnd(event){
    console.log("点击了canva,", event.changedTouches[0])
    console.log("点击了canva,", event.changedTouches[0].x,event.changedTouches[0].y)
    let touch_x=event.changedTouches[0].x, touch_y = event.changedTouches[0].y
    if(this.data.need_click_x===-1&&this.data.need_click_y===-1){
        wx.showToast({
            title: '暂无分步引导',
            icon:'success',
            duration: 500
        })
    }
    else if(Math.abs(this.data.need_click_x-touch_x)<(this.data.width/6/2)&&Math.abs(this.data.need_click_y-touch_y)<(this.data.width/6/2)){
        this.next()
    }
    else{
        wx.showToast({
            title: '请根据引导点击',
            icon:'error',
            duration: 500
        })
    }
  },
    myDraw1(){
        let that=this
        //首先清空画布
        that.data.ctx.clearRect(0, 0, that.data.width,that.data.height)
        // 第一次进入画第一张图片和指示区域
        const bg = that.data.canvas.createImage()
        bg.src = that.data.imgList[that.data.count].demo
        bg.onload = () => {
        //   console.log("画布的信息是",that.data.width,that.data.height)
        //   console.log("绘画图片原始信息是",bg.width,bg.height)
          const [x,y,w,h] = that.computeCanvasImageLocation(that.data.width,that.data.height,bg.width,bg.height)
          console.log("绘画图片位置是",x,y,w,h)
          that.data.ctx.drawImage(bg, x, y, w, h)
          let circleLocation = that.data.imgList[that.data.count].location
          if(!circleLocation||circleLocation.length<1){
              wx.showToast({
                  title: '暂无分步引导',
                  icon:'success',
                  duration: 500
              })
              that.setData({
                need_click_x: -1,
                need_click_y: -1
              })
          }
          else{
            const [c_x,c_y] = that.computeCanvasCircleLocation(that.data.width,that.data.height,bg.width,bg.height,parseInt(circleLocation[0]),parseInt(circleLocation[1]))
            console.log("引导区域是",circleLocation,c_x,c_y)
            //画引导区域
            that.data.ctx.lineWidth = 5
            that.data.ctx.beginPath()
            that.data.ctx.arc(c_x, c_y, that.data.width/6, 0, 2 * Math.PI)	//绘制圆圈
            that.data.ctx.strokeStyle='red'
            that.data.ctx.stroke()
            that.setData({
            need_click_x: c_x,
            need_click_y: c_y
            })

            //画手指引导手势
            const finger = that.data.canvas.createImage()
            finger.src = '/image/prompt_finger.png'
            finger.onload = () => {
                const f_x=c_x,f_y=c_y
                const f_w=w/3,f_h = Math.floor((f_w/finger.width)*finger.height)
                that.data.ctx.drawImage(finger, f_x, f_y, f_w, f_h)
                console.log("手指是：",f_x, f_y, f_w, f_h,"\n")
            }
          }
           
        }
    },

    // 根据画布大小和图片原始宽高计算绘画图片的宽和高,以及绘画起始的位置
    computeCanvasImageLocation(canvas_w,canvas_h,i_w,i_h){
        let w,h
        h=canvas_h
        w=Math.floor((h/i_h)*i_w)
        let x,y
        y=0
        x=Math.floor((canvas_w-w)/2)
        return [x,y,w,h]
    },
    computeCanvasCircleLocation(canvas_w,canvas_h,i_w,i_h,c_x,c_y){
        let ratio=canvas_h/i_h
        c_x=Math.floor(ratio * c_x) + Math.floor((canvas_w-Math.floor((canvas_h/i_h)*i_w))/2)
        c_y=Math.floor(ratio * c_y)
        return [c_x,c_y]
    },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    console.log("课程分步学习页面的course id是：", options.id)
    wx.request({
      url: API.GetCourseDetail,
      header:{
        "Authorization": 'Bearer '+wx.getStorageSync('accessTokenData').accessToken
      },
      method: "get",
      data: {
        id:options.id
      },
      success: (res) => {
        let data = res.data
        console.log('加载课程详情是 :',data)
        let maxStepTemp = 0;
        if(data.data.courseItemId){
          for(let i=0;i<data.data.items.length;i++){
            if(data.data.courseItemId===data.data.items[i].id){
              maxStepTemp = i
              break
            }
          }
        }
        console.log("学习到",maxStepTemp,'步了！')
        this.setData({
          detailData: data.data,
          imgList: data.data.items.filter(item => item.type == 1),
          maxStep: maxStepTemp,
          maxStepLastTime: maxStepTemp
        })
        wx.setNavigationBarTitle({
          title: data.data.name,
        })
        if(maxStepTemp<1){
          wx.showModal({
            title: '音量提示',
            content: '请开启手机音量',
            showCancel: false,
            confirmText: '我知道了'
          })
        }

        // 绘画第一步
        if(this.data.ctx){
            this.myDraw1()
        }
        // 文字转语音第一步
        if(this.data.play_list.length-1<this.data.count)
        {
          // let lto = item.lto || 'en_US'
          let lto = 'zh_CN'
          let content_text = "第"+(this.data.count+1).toString()+"步" + this.data.imgList[this.data.count].description

          this.tts(lto, content_text, this.data.count)
        }
        else{
          // 自动播放
        this.tapSpeech()
        }
      },
      fail: (err) => {
        wx.showModal({
          title: '提示',
          content: JSON.stringify(err),
        })
        console.log(err);
      },
      complete:()=>{
        
      }
    }) 
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

      //页面加载完成之后获取画布canva并存储成为全局变量进行绘画
      let that = this;
      let query = wx.createSelectorQuery().in(this);
      //定义全局canvas
      query.select('#stepCanvas').fields({node: true,size: true}).exec((res) => {
        // Canvas 对象
        const canvas = res[0].node
        // Canvas 画布的实际绘制宽高
        const renderWidth = res[0].width
        const renderHeight = res[0].height
        // Canvas 绘制上下文
        const ctx = canvas.getContext('2d')

        // 初始化画布大小
        const dpr = wx.getWindowInfo().pixelRatio
        canvas.width = renderWidth * dpr
        canvas.height = renderHeight * dpr
        ctx.scale(dpr, dpr)
        that.setData({
          width: res[0].width,
          height: res[0].height,
          ctx: ctx,
          canvas:canvas
        })  
        if(this.data.imgList.length>0){
          that.myDraw1()
        }
      })

    //   query.select('.img-view').boundingClientRect(rect=>{
    //     console.log("渲染之后的图片区域的宽高是：",rect.width,rect.height);
    //     }).exec();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {
    console.log("隐藏页面",this.data.maxStepLastTime,this.data.maxStep)
    this.uploadStep()
    this.playAnimationEnd()
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    console.log("卸载页面",this.data.maxStepLastTime,this.data.maxStep)
    this.uploadStep()
    this.playAnimationEnd()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})